package com.example.juccode.juc01threadpool.demo04.Task;

import java.util.concurrent.RecursiveTask;

/**
 * @description: TODO
 * @date 2025/11/4 17:00
 */
public class ForkJoinTask01 extends RecursiveTask<Integer> {
    /**
     * 起始值
     */
    private int start;
    /**
     * 结束值
     */
    private int end;
    /**
     * 临界值
     */
    private int temp = 10;

    public ForkJoinTask01(int start, int end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Integer compute() {
        //当开头与结束之差小于临界值时，则直接计算
        if (end - start < temp) {
            int sum = 0;
            //循环累加
            for (int i = start; i <= end; i++) {
                sum += i;
            }
            //返回结果
            return sum;
        } else {
            //否则，则进行任务拆分
            int middle = (start + end) / 2;
            System.out.println("拆分："+ middle + "--" + Thread.currentThread().getName());
            //创建任务
            ForkJoinTask01 leftTask = new ForkJoinTask01(start, middle);
            //创建任务
            ForkJoinTask01 rightTask = new ForkJoinTask01(middle + 1, end);
            //执行任务
            leftTask.fork();
            rightTask.fork();
            //获取结果
            Integer leftResult = leftTask.join();
            Integer rightResult = rightTask.join();
            //返回结果
            return leftResult + rightResult;
        }
    }
}
